package com.bolt.admin.security.shiro.matcher;


import com.bolt.admin.exception.BizExceptionEnum;
import com.bolt.admin.security.shiro.exception.AuthErrorException;
import com.bolt.admin.security.shiro.jwt.TokenProvider;
import com.bolt.common.utils.SpringContextUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import io.jsonwebtoken.UnsupportedJwtException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;

/**
 * Created by Administrator on 2018/11/22.
 */

public class JwtMatcher implements CredentialsMatcher {


    @Override
    public boolean doCredentialsMatch(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {
        TokenProvider tokenProvider = SpringContextUtil.getBean(TokenProvider.class);
        String authToken = (String) authenticationInfo.getCredentials();
        try {
            tokenProvider.parseToken(authToken);
        }catch (UnsupportedJwtException|MalformedJwtException|SignatureException|IllegalArgumentException e){// 令牌错误
            throw new AuthErrorException(BizExceptionEnum.TOKEN_ERROR);
        }catch (ExpiredJwtException ex){// 令牌过期
            throw new AuthErrorException(BizExceptionEnum.TOKEN_EXPIRED);
        }
        return true;
    }


}